from openpyxl import load_workbook
from math import ceil
import sys
sys.path.append("..")
from functional.utils import SPLIT_FUNC_DICT, JOIN_STR_DICT, EXTRACT_FUNC_DICT
from traceback import format_exc

def load_translate_map(translate_workbook_name):
	res = {}
	wb = load_workbook(translate_workbook_name, data_only=True)
	sh = wb["Sheet1"]
	num_coll = sh.cell(1, 2).value
	for j in range(4, 4+num_coll):
		num_keyword = sh.cell(1, j).value
		coll_name = sh.cell(2, j).value
		res[coll_name] = []
		for i in range(3, 3+num_keyword):
			res[coll_name].append(sh.cell(i, j).value.lower())
	return res

def translate_addr(addr, translate_map):
	res = []

	for coll in translate_map:
		for keyword in translate_map[coll]:
			if keyword in addr:
				res.append(coll)
				break

	return ",".join(res)

def translate_single_record(record, translate_map, other_flag, addr_type, bind_author_flag):
	res = []
	if bind_author_flag:
		extract_func = EXTRACT_FUNC_DICT[addr_type]

	for i in record:
		# 外校地址直接跳过
		if "外校" in i:
			res.append(i)
		else:
			tmp = translate_addr(i.lower(), translate_map)
			# 绑定作者
			if bind_author_flag:
				row = []
				# 提取作者列表
				author_list = extract_func(i)
				# 翻译失败
				if tmp == "":
					# 将翻译失败的转为“其他”
					if other_flag:
						# 遍历作者列表，将作者与翻译结果拼接
						for author in author_list:
							row.append(f"{author}-其他")
				else:
					for author in author_list:
						row.append(f"{author}-{tmp}")

				res.append("|".join(row))
			else:
				if tmp == "":
					if other_flag:
						res.append("其他")
				else:
					res.append(tmp)

	return ";".join(res)

def translate_func(args):
	try:
		workbook_file_name = args[0]
		output_file_name = args[1]
		sheet_name = args[2]
		row_from = args[3]
		row_to = args[4]
		data_cols = args[5]
		translate_workbook_name = args[6]
		other_flag = args[7]
		signal = args[8]
		signal.emit("启动地址翻译任务\n开始加载EXCEL文件")

		wb = load_workbook(workbook_file_name)
		signal.emit("完成EXCEL文件加载\n开始翻译地址")
		sh = wb[sheet_name]

		translate_map = load_translate_map(translate_workbook_name)

		for data_col in data_cols:
			input_col = data_col[1]
			output_col = data_col[2]
			addr_type = data_col[3]
			bind_author_flag = data_col[4]

			split_func = SPLIT_FUNC_DICT[addr_type]
			if row_from > 1:
				sh.cell(row_from-1, output_col).value = data_col[0]

			length = row_to - row_from + 1
			step = ceil(length*0.1)
			for i in range(row_from, row_to+1):
				addr_str = sh.cell(i, input_col).value
				addr = split_func(addr_str)
				translate_result = translate_single_record(addr, translate_map, other_flag, addr_type, bind_author_flag)
				sh.cell(i, output_col).value = translate_result

				cnt = i - row_from + 1
				if cnt % step == 0:
					signal.emit(f"{data_col[0]}: {cnt/length*100:.2f}%")
		
		signal.emit("完成地址翻译\n开始写入结果")
		wb.save(output_file_name)
		signal.emit("完成结果写入")

	except Exception as e:
		signal = args[8]
		signal.emit(f"翻译失败：{e}\n追踪信息：{format_exc()}")
